module SCPU_ctrl(
	input [4:0] OPcode,
	input [2:0] Fun3,
	input Fun7,
	input MIO_ready,
	output reg [1:0] ImmSel,
	output reg ALUSrc_B,
	output reg [1:0] MemtoReg,
	output reg Jump,
	output reg Branch,
	output reg RegWrite,
	output reg MemRW,
	output reg [2:0] ALU_Control,
	output reg CPU_MIO
    );
    
    reg [1:0] ALUop;
    wire [3:0] Fun;
    assign Fun={Fun3,Fun7};
    
    always @(*) begin
    	case(OPcode)
    	5'b01100:begin	//R型
    		ImmSel=2'd0;
    		ALUSrc_B=1'b0;
    		MemtoReg=2'd0;
    		Jump=1'b0;
    		Branch=1'b0;
    		RegWrite=1'b1;
    		MemRW=1'b0;
    		ALUop=2'b10;
    		end
    	5'b00100:begin	//I型
    		ImmSel=2'd0;
    		ALUSrc_B=1'b1;
    		MemtoReg=2'd0;
    		Jump=1'b0;
    		Branch=1'b0;
    		RegWrite=1'b1;
    		MemRW=1'b0;
    		ALUop=2'b11;
    		end
    	5'b00000:begin	//lw
    		ImmSel=2'd0;
    		ALUSrc_B=1'b1;
    		MemtoReg=2'd1;
    		Jump=1'b0;
    		Branch=1'b0;
    		RegWrite=1'b1;
    		MemRW=1'b0;
    		ALUop=2'b00;
    		end
    	5'b01000:begin 	//sw
    		ImmSel=2'd1;
    		ALUSrc_B=1'b1;
    		MemtoReg=2'd0;
    		Jump=1'b0;
    		Branch=1'b0;
    		RegWrite=1'b0;
    		MemRW=1'b1;
    		ALUop=2'b00;
    		end
    	5'b11000:begin	//beq
    		ImmSel=2'd2;
    		ALUSrc_B=1'b0;
    		MemtoReg=2'd0;
    		Jump=1'b0;
    		Branch=1'b1;
    		RegWrite=1'b0;
    		MemRW=1'b0;
    		ALUop=2'b01;
    		end
    	5'b11011:begin	//jal
    		ImmSel=2'd3;
    		ALUSrc_B=1'b1;
    		MemtoReg=2'd2;
    		Jump=1'b1;
    		Branch=1'b0;
    		RegWrite=1'b1;
    		MemRW=1'b0;
    		ALUop=2'b00;
    		end
    	endcase
    end
    
    always @(*) begin
    	case(ALUop)
    		2'b00:ALU_Control=3'b010;
    		2'b01:ALU_Control=3'b110;
    		2'b10:begin
    			case(Fun)
    				4'b0000:ALU_Control=3'b010;	//add
    				4'b0001:ALU_Control=3'b110;	//sub
    				4'b1110:ALU_Control=3'b000;	//and
    				4'b1100:ALU_Control=3'b001;	//or
    				4'b0100:ALU_Control=3'b111;	//slt
    				4'b1000:ALU_Control=3'b011;	//xor
    				4'b1010:ALU_Control=3'b101;	//srl
    				default:ALU_Control=3'bx;
    			endcase
    		end
    		2'b11:begin
    			case(Fun3)
    				3'b000:ALU_Control=3'b010;	//addi
    				3'b111:ALU_Control=3'b000;	//and
    				3'b110:ALU_Control=3'b001;	//ori
    				3'b100:ALU_Control=3'b011;	//xori
    				3'b010:ALU_Control=3'b111;	//slti
    				3'b101:ALU_Control=3'b101;	//srli
    			endcase
    		end
    	endcase
    end
    				
endmodule